/**
 * Created by Administrator on 2017/2/14.
 */

var BASE_PATH = "/wxpay";
var OPEN_PATH = "http://120.26.247.222:10099/openapi";
var PAY_PATH = BASE_PATH + "/pay"

var userId = getCookie("userId");
var memberId = getQueryString("state");

getUserId();
getMemberId();
/**
 * 微信支付事件
 * @param url
 * @param data
 */
function toPay(url,data) {
    if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', function() {
                onBridgeReady(url,data);
            }, false);
        } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', function() {
                onBridgeReady(url,data);
            });
            document.attachEvent('onWeixinJSBridgeReady', function() {
                onBridgeReady(url,data);
            });
        }
    } else {
        onBridgeReady(url,data);
    }
}
/**
 * 调用微信JS api 支付
 * @param url
 * @param data
 */
function onBridgeReady(url,data) {
    $.ajax({
        type : "POST",
        url : url,
        dataType : 'json', // 返回json格式数据
        data : data,
        cache : false,
        error : function() {
            alert("支付异常,充值结果未知。请查询订单");
        },
        success : function(wcPay) {
            WeixinJSBridge.invoke('getBrandWCPayRequest', {
                appId : wcPay.appId,
                timeStamp : wcPay.timeStamp,
                nonceStr : wcPay.nonceStr,
                package : wcPay.package,
                signType : wcPay.signType,
                paySign : wcPay.paySign
            }, function(res) {
                if (res.err_msg == "get_brand_wcpay_request:ok") {
//					alert("恭喜您，下单成功!");
                }else if(res.err_msg == "get_brand_wcpay_request:cancel"){
//					alert("您取消了支付");
                }else{
                    alert("支付异常,充值结果未知。请查询订单。谢谢");
                }
            });
        }
    });

}

/**
 * 获取memberId
 */
function getMemberId() {
    if (isNull(memberId)) {
        memberId = getCookie("memberId");
    }
    setCookie("memberId", memberId);
}
/**
 * 获取url参数
 *
 * @param name
 * @returns
 */
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null)
        return unescape(r[2]);
    return null;
}
/**
 * 获取用户 UserID
 */
function getUserId() {
    if (!isNull(userId)) {
        return;
    }
    var code = getQueryString("code");
    $.ajax({
        type : "POST",
        url : BASE_PATH + "/oauth",
        dataType : 'json', // 返回json格式数据
        data : {
            "code" : code,
        }, // 数据
        cache : false,
        success : function(msg) {
            if (isNull(msg)) {
                // alert("请在微信客户端打开链接");
                return;
            }
            userId = msg.openid;
            setCookie("userId", userId);
        }
    });
}
/**
 * 设置Cookie
 *
 * @param name
 * @param value
 */
function setCookie(name, value) {
    var hour = 1;
    var exp = new Date();
    exp.setTime(exp.getTime() + hour * 60 * 60 * 1000);//1000个小时后过期
    document.cookie = name + "=" + escape(value) + ";expires="
        + exp.toGMTString();
}
/**
 * 获取Cookie
 *
 * @param name
 * @returns
 */
function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}
/**
 * 删除Cookie
 *
 * @param name
 */
function delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null)
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}
/**
 * 设置当前金额
 */
function setPrice(obj) {
    var dimension = $(obj).attr("dimension");
    var sale = $(obj).attr("sale");
    // 样式修改
    $("a[name='priceTag']").find("p").css({
        "color" : "#000"
    });
    var selected = $(obj).children("p").children("span");
    selected.text("售价 ¥" + ceil4Float(sale,2));
    selected.parent().css({
        "margin-top" : "-10px",
        "color" : "red"
    });
    // 定值
    $("#hiddenDimension").val(dimension);
    // 话费充值页面 隐藏自定义面额控件
    $("#otherPrice_div").hide();
}

/**
 * 开关其他面额隐藏项
 */
function toggleOther() {
    $('.hiddenSpn').toggle();
}

/**
 * 检测手机号是否正确
 *
 * @param val
 * @returns {Boolean}
 */
function checkPhoneNum(val) {
    var phone_numReg = /^0{0,1}(13[0-9]|14[0-9]|17[0-9]|15[0-9]|18[0-9])[0-9]{8}$/;
    return phone_numReg.test(val);
}

/**
 * 验证金额
 *
 * @param price
 * @returns {Boolean}
 */
function checkPrice(price) {
    return (/^(([1-9]\d*)|\d)(\.\d{1,2})?$/).test(price.toString());
}
/**
 * 验证金额(输入一半)
 *
 * @param price
 * @returns {Boolean}
 */
function checkHalfPrice(price) {
    return (/^(([0-9]\d*)|\d)(\.)$/).test(price.toString());
}
/**
 * 验证空内容
 *
 * @param val
 * @returns
 */
function isNull(val) {
    return (null == val || "" == val || undefined == val || "undefined" == val);
}
/**
 * 创建一个产品item
 *
 * @param dimension
 * @param sale
 * @param product
 * @returns {String}
 */
function newProItem(dimension, sale, product) {
    return "<a href='javascript:;' name='priceTag' dimension="
        + dimension
        + " sale="
        + sale
        + " class='weui_grid js_grid' onclick=\"setPrice(this);\">"
        + "<p class='weui_grid_label'>"
        + ((product == 4 || product == 5) ? (dimension < 1024 ? dimension
                + "M" : dimension / 1024 + "G") : dimension + "元") + "<br>"
        + "<span class='priceTag_class'></span>" + "</p> " + "</a>";
}
/**
 * 创建一个无配置产品信息item
 *
 * @returns {String}
 */
function newNoProItem() {
    return "<span style='width: 90%;text-align: center; margin-top: 10px; color: #888; font-size:12px;'>"
        + "<style>#PriceTag_Div{text-align: center;}</style>"
        + "<b>暂未配置产品数据</b>" + "</span>";
}
/**
 * 进一法 保留n位小数
 * @param num 数字
 * @param n 保留位数
 * @returns
 */
function ceil4Float(num,n){
    if (isNaN(num)) {
        return num;
    }
    if (isNull(n)) {
        n=2;
    }
    var multiple = Math.pow(10,n);
    var temp = Math.ceil((num*multiple).toFixed(n));
    result = (temp/multiple).toFixed(n);
    return result;
}